package com.hu.video.service.impl;

import com.hu.video.entity.SocialCommentLike;
import com.hu.video.mapper.SocialCommentLikeMapper;
import com.hu.video.mapper.SocialCommentMapper;
import com.hu.video.service.ISocialCommentLikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;

@Service
public class SocialCommentLikeServiceImpl implements ISocialCommentLikeService {
    @Autowired
    private SocialCommentLikeMapper likeMapper;
    @Autowired
    private SocialCommentMapper commentMapper;

    @Override
    public boolean likeComment(Long commentId, Long userId) {
        if (likeMapper.selectByCommentAndUser(commentId, userId) != null) return true; // 已点赞直接返回true
        SocialCommentLike like = new SocialCommentLike();
        like.setCommentId(commentId);
        like.setUserId(userId);
        like.setCreatedAt(new java.util.Date());
        try {
            boolean result = likeMapper.insertLike(like) > 0;
            if(result) {
                int count = likeMapper.countLikes(commentId);
                commentMapper.updateLikeCount(commentId, count);
            }
            return result;
        } catch (Exception e) {
            // 捕获唯一索引冲突异常，说明已经点过赞，直接返回true
            if (e.getCause() != null && e.getCause().getMessage() != null && e.getCause().getMessage().contains("Duplicate entry")) {
                return true;
            }
            throw e; // 其他异常继续抛出
        }
    }

    @Override
    public boolean unlikeComment(Long commentId, Long userId) {
        boolean result = likeMapper.deleteLike(commentId, userId) > 0;
        if(result) {
            int count = likeMapper.countLikes(commentId);
            commentMapper.updateLikeCount(commentId, count);
        }
        return result;
    }

    @Override
    public int getLikeCount(Long commentId) {
        return likeMapper.countLikes(commentId);
    }

    @Override
    public boolean isLiked(Long commentId, Long userId) {
        return likeMapper.selectByCommentAndUser(commentId, userId) != null;
    }
} 